﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PhotoGalleryEnteties;

namespace PhotogalleryModel
{
    public class GalleryUserRepository
    {

        public const string DefaultUserRole = "user";
        
        public GalleryUserRepository (ModelContext modelContext)
        {
            _context = modelContext.Context;
        }

        private IContext _context;

        public GalleryUser  CreateUser()
        {
            GalleryUser user =_context.CreateObject<GalleryUser>();
            user.CreateDate = DateTime.Now;
            user.RoleName = "user";
            return user;
        }


       public void DeleteUser(GalleryUser user)
       {
           if (user == null)
               throw new ArgumentNullException();
           _context.DeleteObject(user);
       }
        
        public void DeleteUser(string loweredUserName  )
        {
            GalleryUser userToDelete =
                _context.GalleryUsers.Where(p => p.UserName.ToLower() == loweredUserName).FirstOrDefault();
            if (userToDelete  == null)
                throw new GalleryModelException(string.Format("User with name{0} doesn`t exist", loweredUserName));
            _context.DeleteObject(userToDelete);
        }

        #region SelectMethods

        public GalleryUser GetUserByName(string UserName)
        {
            UserName=UserName.ToLower();
            GalleryUser user = _context.GalleryUsers.Where(p => p.UserName.ToLower() ==UserName).FirstOrDefault();
            if (user == null)
                throw new GalleryModelException(string.Format("User with name{0} doesn`t exist",UserName));
            return user;
        }

        public IQueryable <GalleryUser> GetAllUsers()
        {
            return _context.GalleryUsers;
        }


        public ItemsPage<GalleryUser > GetUsersPage(int onPage,int currentPage ,out int totalPages )
        {
            return _context.GalleryUsers.GetPage(onPage, currentPage, out totalPages);
        }


        public bool UsenameExists(string name)
        {
            return _context.GalleryUsers.Where(p => p.UserName == name).FirstOrDefault() != null;
        }

        public bool CheckEmail(string email)
        {
            return _context.GalleryUsers.Where(p => p.Email == email).FirstOrDefault() != null;
        }
        
        #endregion

        public IEnumerable< string> GetAllowedRoles()
        {
            return _context.GetAllowedRoles();
        }



    }
}
